package com.moyun.websocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;

/**
 * 握手拦截器WebSocketHandshakeInterceptor
 * <设置认证用户信息的握手拦截器>
 **/
@Slf4j
public class MyPrincipalHandshakeHandler extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {

        //这里就是简单
        HttpSession session = getSession(request);
        if (session != null) {

            if (isCopyHttpSessionId()) {

                attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
            }
            Enumeration<String> names = session.getAttributeNames();
            while (names.hasMoreElements()) {

                String name = names.nextElement();
                if (isCopyAllAttributes() || getAttributeNames().contains(name)) {

                    attributes.put(name, session.getAttribute(name));
                }
            }
        }
        return true;
    }

    /**
     * @return javax.servlet.http.HttpSession
     * @Author yangboxuan
     * @Description 获取 HttpSession 会话
     * @Date 2021/6/25 20:32
     * @Param [request]
     */
    private HttpSession getSession(ServerHttpRequest request) {

        if (request instanceof ServletServerHttpRequest) {

            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            return serverRequest.getServletRequest().getSession(false);
        }
        return null;
    }
}